/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/

package com.datasentinel.util.data;


/**
 * 
 * @author Areg Beketovski
 *
 */

public class BoundedByteArray extends ByteArray
{
	private static final long serialVersionUID = 1L;

	private int maxIndex = -1;
	
	public BoundedByteArray(int size)
	{
		super(size);
	}

	public int dataLength()
	{
		return super.length();
	}
	
	@Override
	public int length()
	{
		return super.length() < (maxIndex + 1) ? super.length() : (maxIndex + 1); 
	}

	public void set(ReadOnlyByteArray byteArray, int offset, int length) throws ArrayIndexOutOfBoundsException
	{
		setMaxIndex(length - 1);
		set(0, byteArray, offset, length);
	}
	
	public void set(byte[] data, int offset, int length) throws ArrayIndexOutOfBoundsException
	{
		setMaxIndex(length - 1);
		set(0, data, offset, length);
	}
	
	
	public void setMaxIndex(int maxIndex) throws ArrayIndexOutOfBoundsException
	{
		if(maxIndex < 0 || maxIndex >= super.length())
			throw new ArrayIndexOutOfBoundsException("Invalid array index: " + maxIndex);
			
		this.maxIndex = maxIndex;
		
		if(this.outputStream != null && this.outputStream instanceof GrowingByteArrayOutputStream)
		{
			this.data = ((GrowingByteArrayOutputStream)this.outputStream).getByteArray();
		}
		
	}

//	public void setMaxIndexAndGrowIfNeeded(int maxIndex) throws ArrayIndexOutOfBoundsException
//	{
//		if(maxIndex < 0)
//			throw new ArrayIndexOutOfBoundsException("Invalid array index: " + maxIndex);
//		
//		this.maxIndex = maxIndex;
//		
//		if(maxIndex > super.length())
//		{
//			byte[] oldData = this.data;
//			this.data = new byte[this.maxIndex + 1];
//			System.arraycopy(oldData, 0, this.data, 0, oldData.length);
//			oldData = null;
//		}
//	}

	@Override
	protected void createOutputStream(int offset)
	{
		this.outputStream = new GrowingByteArrayOutputStream(this.data);
	}
	
}
